package easy;

import java.util.HashMap;
import java.util.Map;
/*
1160. 拼写单词
 */
public class LeeCode1160 {

  public int countCharacters(String[] words, String chars) {

//    统计chars里边的字符情况
    Map<Character, Integer> charInt = new HashMap<Character, Integer>();
    for (int i = 0; i < chars.length(); i++) {
      char c = chars.charAt(i);
      charInt.put(c, charInt.getOrDefault(c, 0) + 1);
    }

    int count = 0;

//    先统计words数组中每个数组的字符情况，再拿单个单词去跟chars的情况比较，只要单词的每个字符的数量都小于chars中的字符的数量，即可拼出该单词
    for (String word : words) {
      Map<Character, Integer> wordCnt = new HashMap<Character, Integer>();
//      统计每个单词
      for (int i = 0; i < word.length(); i++) {
        char c = word.charAt(i);
        wordCnt.put(c, wordCnt.getOrDefault(c, 0) + 1);
      }
//      判断
      boolean isAns = true;
      for (int i = 0; i < word.length(); ++i) {
        char c = word.charAt(i);
        if (charInt.getOrDefault(c, 0) < wordCnt.getOrDefault(c, 0)) {
          isAns = false;
          break;
        }
      }
      if (isAns) {
        count += word.length();
      }
    }
    return count;
  }

  public static void main(String[] args) {

    String[] words = new String[]{"cat","bt","hat","tree"};
    System.out.println(new LeeCode1160().countCharacters(words, "atach"));
  }
}
